package org.glavo.bot.data

import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import org.glavo.bot.bot
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.ConcurrentHashMap
import kotlin.io.path.absolute
import kotlin.io.path.exists

object PersistentStorage {
    private val path = Paths.get("storage.json").absolute()
    private val data: MutableMap<String, JsonElement> = ConcurrentHashMap()
    private val jo = JsonObject(data)

    init {
        if (path.exists()) {
            try {
                data.putAll(Json.parseToJsonElement(Files.readString(path)).jsonObject)
            } catch (e: Throwable) {
                bot.logger.warning("加载 $path 失败", e)
            }
        } else {
            bot.logger.info("$path 不存在")
        }
    }

    private fun save() {
       Files.writeString(path, jo.toString())
    }

    operator fun get(key: String): JsonElement? = data[key]
    operator fun set(key: String, value: JsonElement) {
        synchronized(this) {
            data[key] = value
            save()
        }
    }
}